<?php

function CABLE_adminSignup()
{
	global $cable_admin_plugin;
	
	/* swap the action template, and check for sanity */
	$old_action_template = $cable_admin_plugin[action_template];
	$cable_admin_plugin[action_template] = $cable_admin_plugin[action_template]->GetChild('CABLE-SignupPage');
	if ($cable_admin_plugin[action_template] === false)
		return 'Error retrieving signup page';
	
	/* just show the sign up template */
	if ($_REQUEST['signup_username'] == '')
		return true;

	$error = false;
	
	/* make sure passwords match */
	if ($_REQUEST['signup_password1'] != $_REQUEST['signup_password2'])
		$error = 'Passwords did not match.';

	/* make sure password is ok */
	if (strlen($_REQUEST['signup_password1']) < 8)
		$error = 'Password must be at least 8 characters long.';
		
	$username = str_replace('"','',str_replace('\'','',urldecode($_REQUEST['signup_username'])));
	if (strlen($username) < 4)
		$error = 'Username must be at least 4 characters long.';
		
	/* verify that email is valid */
	$email= str_replace('"','',str_replace('\'','',urldecode($_REQUEST['signup_email'])));
	if (!CABLE_verifyMailbox($email))
		$error = 'Email is not valid.';
		
	/* verify that username doesn't already exist */
	$table = "cable_".$cable_admin_plugin[connector]->config['TablePrefix']."_users";
	$query = "SELECT COUNT(*) FROM $table WHERE (username = '".$username."') LIMIT 1";
	if ($result = mysql_query($query,$cable_admin_plugin[connector]->db_link))
	{
		$row = mysql_fetch_row($result);
		if ($row[0] != 0)
			$error = 'Username already exists.';
	}
	else
		return 'Error reading user database table.';
	
	$fullname = addslashes($_REQUEST['signup_fullname']);
	$password = md5($username.urldecode($_REQUEST['signup_password1']));
	
	if ($error !== false)
	{
		$cable_admin_plugin[action_template]->SetBool('CABLE-Error',true);
		$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Error.text',$error);
	}
	else
	{
		/* insert record into database */
		$query = "INSERT INTO $table (username,fullname,adminlevel,email,password) VALUES('$username','$fullname',0,'$email','$password')";
		if (($result = mysql_query($query,$cable_admin_plugin[connector]->db_link)) === false)
			return 'Error writing user information to database'.mysql_error();
	
		/* load signup template to the action template, and check for sanity */
		$cable_admin_plugin[action_template] = $old_action_template->GetChild('CABLE-SignupPage');
		if ($cable_admin_plugin[action_template] === false)
			return 'Error retrieving signup page';
			
		$cable_admin_plugin[action_template]->SetBool('CABLE-Notice',true);
		$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Notice.text','You have successfully signed up.');
		return true;
	}
	
	/* do template replacements */
	$cable_admin_plugin[action_template]->SetBool('CABLE-Error',false);
	$cable_admin_plugin[action_template]->SetBool('CABLE-Notice',false);
	$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Signup.email',$email);
	$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Signup.username',$username);
	$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Signup.fullname',$fullname);
		
	return true;
}

function CABLE_adminLogin()
{
	global $cable_admin_plugin;

	/* load login template to the action template, and check for sanity */
	$cable_admin_plugin[action_template] = $cable_admin_plugin[action_template]->GetChild('CABLE-LoginPage');
	if ($cable_admin_plugin[action_template] === false)
		return 'Error retrieving login page';

	/* user tried logging in, but failed */
	if (($_REQUEST['username']) && (!$cable_admin_plugin[connector]->user->logged_in))
	{
		$cable_admin_plugin[action_template]->SetBool('CABLE-Error',true);
		$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Error.text','Incorrect username or password.');
	}
	elseif ($cable_admin_plugin[connector]->user->logged_in)
	{
		/* save auth information to cookies */
		if ($_REQUEST['login_remember'] == 'true')
			setcookie('CABLE_auth',$cable_admin_plugin[connector]->user->values[username].','.$cable_admin_plugin[connector]->user->values[password],time().$cable_admin_plugin[connector]->config[CookieTimeout]);
		else
			setcookie('CABLE_auth',$cable_admin_plugin[connector]->user->values[username].','.$cable_admin_plugin[connector]->user->values[password],0);
	}
	
	return true;
}

function CABLE_adminLogout()
{
	global $cable_admin_plugin;
	
	/* delete the authorization cookie */
	setcookie('CABLE_auth','',time() - 3600);
	
	/* tell the user object to log out */
	$cable_admin_plugin[connector]->user->LogOut();
			
	$cable_admin_plugin[action_template] = $cable_admin_plugin[action_template]->GetChild('CABLE-LoginPage');
	if ($cable_admin_plugin[action_template] === false)
		return 'Error retrieving login page';
	
	$cable_admin_plugin[action_template]->SetBool('CABLE-Error',true);
	$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Error.text','You have succesfully logged out.');

	return true;
}

function CABLE_adminLost()
{
	global $cable_admin_plugin;
	
	/* archive the original action template for future use, and the swap out the active one for the necessary panel */
	$old_action_template = $cable_admin_plugin[action_template];
	$cable_admin_plugin[action_template] = $cable_admin_plugin[action_template]->GetChild('CABLE-LostPasswordPage');
	if ($cable_admin_plugin[action_template] === false)
		return 'Error retrieving lost password page';
	
	$table = "cable_".$cable_admin_plugin[connector]->config['TablePrefix']."_users";
	if ($_REQUEST['account_email'] != '') /* request to send out an email */
	{
		$cable_admin_plugin[action_template]->SetBool('CABLE-Request',true);
		$cable_admin_plugin[action_template]->SetBool('CABLE-Reset',false);
		
		$email = str_replace('"','',str_replace('\'','',$_REQUEST['account_email']));
		
		$query = "SELECT username,password FROM $table WHERE (email = '$email') LIMIT 1";
		if ($result = mysql_query($query,$cable_admin_plugin[connector]->db_link))
		{
			if (mysql_num_rows($result) < 1)
			{
				$cable_admin_plugin[action_template]->SetBool('CABLE-Error',true);
				$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Error.text','No account with that e-mail exists.');
				return true;
			}
			
			$user_data = mysql_fetch_assoc($result);
			
			$email_template = $old_action_template->GetChild('CABLE-LostPasswordEmail');
			if ($email_template === false)
				return 'Error retrieving password reset message template';
			
			$email_template->ReplaceInsert('CABLE-Base.url',$cable_admin_plugin[connector]->config[SiteURL]);
			$email_template->ReplaceInsert('CABLE-Account.username',$user_data[username]);
			$email_template->ReplaceInsert('CABLE-Account.hash',$user_data[password]);
			
			$title = $email_template->GetValue('CABLE-Title');
			$headers = 'From: '.$email_template->GetValue('CABLE-Address')."\r\n";
			$text = str_replace("\n.","\n..",$email_template->Render());

			if (mail($email,$title,$text,$headers))
			{
				$cable_admin_plugin[action_template]->SetBool('CABLE-Notice',true);
				$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Notice.text','An email has been sent to the account address.');
			}
			else
			{
				$cable_admin_plugin[action_template]->SetBool('CABLE-Error',true);
				$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Error.text','Could not send an e-mail to the account address.');
			}
		}
		else
			return 'Error accessing user database table';
	}
	elseif ($_REQUEST['hash'] != '')  /* display password reset form */
	{
		$cable_admin_plugin[action_template]->SetBool('CABLE-Request',false);
		$cable_admin_plugin[action_template]->SetBool('CABLE-Reset',true);
		
		$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Account.hash',urldecode($_REQUEST['hash']));
		$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Account.username',urldecode($_REQUEST['user']));
	}
	elseif ($_REQUEST['account_hash'] != '') /* request to save new password to database */
	{
		$cable_admin_plugin[action_template]->SetBool('CABLE-Request',false);
	
		$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Account.hash',urldecode($_REQUEST['account_hash']));
		$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Account.username',urldecode($_REQUEST['account_username']));
		
		$error = false;
		/* make sure passwords match */
		if ($_REQUEST['account_password1'] != $_REQUEST['account_password2'])
			$error = 'New passwords did not match.';
		elseif ((strlen($_REQUEST['account_password1']) < 8) && ($_REQUEST['account_password1'] != ''))
			$error = 'New password must be at least 8 characters long.';			

		if ($error !== false)
		{
			$cable_admin_plugin[action_template]->SetBool('CABLE-Error',true);
			$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Error.text',$error);
			$cable_admin_plugin[action_template]->SetBool('CABLE-Reset',true);
			return true;
		}

		$username = str_replace('"','',str_replace('"','',$_REQUEST['account_username']));
		$password = md5($username.urldecode($_REQUEST['account_password1']));	

		$query = "UPDATE $table SET password='$password' WHERE username='$username' LIMIT 1";
		if (($result = mysql_query($query,$cable_admin_plugin[connector]->db_link)) === false)
			return 'Error updating user account information';
				
		$cable_admin_plugin[action_template]->SetBool('CABLE-Reset',false);
		$cable_admin_plugin[action_template]->SetBool('CABLE-Notice',true);
		$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Notice.text','Your account password has been succesfully updated.');
	}
	else
	{
		$cable_admin_plugin[action_template]->SetBool('CABLE-Request',true);
		$cable_admin_plugin[action_template]->SetBool('CABLE-Reset',false);
	}
	
	return true;
}

function CABLE_adminAccount()
{
	global $cable_admin_plugin;
	
	/* load account editing template to the action template, and check for sanity */
	$cable_admin_plugin[action_template] = $cable_admin_plugin[action_template]->GetChild('CABLE-AccountPage');
	if ($cable_admin_plugin[action_template] === false)
		return 'Error retrieving account editing page';
		
	/* array object that will hold account information */
	$account_info = array();
	
	/* don't have a problem...yet */
	$error = false;
	
	/* table name upon which to execute the query */
	$table = "cable_".$cable_admin_plugin[connector]->config['TablePrefix']."_users";
	
	/* form has been sent, save the passed variables into the account info */
	if (($_REQUEST['account_action'] == 'user_edit') || ($_REQUEST['account_action'] == 'admin_edit'))
	{
		/* if it's a user editing his account details, force him to reauthenticate for every edit */
		$cable_admin_plugin[action_template]->SetBool('CABLE-Authenticate',($_REQUEST['account_action'] == 'user_edit'));
		
		$account_info[username] = str_replace('"','',str_replace('\'','',urldecode($_REQUEST['account_username'])));
		$account_info[fullname] = str_replace('"','',str_replace('\'','',urldecode($_REQUEST['account_fullname'])));
		$account_info[email] = str_replace('"','',str_replace('\'','',urldecode($_REQUEST['account_email'])));
		
		if ($_REQUEST['account_action'] == 'user_edit') /* make sure the user has the password right */
		{
			$account_info[password] = md5($account_info[username].urldecode($_REQUEST['account_password']));
			
			$query = "SELECT * FROM $table WHERE (username='".$account_info[username]."') LIMIT 1";
			if (($result = mysql_query($query,$cable_admin_plugin[connector]->db_link)) === false)
				return 'Error reading information from user database table';
			$array = mysql_fetch_assoc($result);
			if ($array[password] != $account_info[password])
			{
				$error = 'Incorrect password.';
				$account_info = $array; /* reset potentially changed fields back to original values */
			}
		}
	}
	elseif($_REQUEST['user_action'] == 'edit_account') /* admin is editing a single account */
	{
		/* admin doesn't need to know the user's password */
		$cable_admin_plugin[action_template]->SetBool('CABLE-Authenticate',false);
		
		/* get the username passed by the user admin form */
		$account_info[username] = str_replace('"','',str_replace('\'','',urldecode($_REQUEST['user_name'])));
		
		/* need to verify that logged in user has admin privileges */
		if ($cable_admin_plugin[connector]->user->values[adminlevel] < 1)
			return true;

		/* verify we can change the user account details, and retrieve the user information */
		$query = "SELECT * FROM $table WHERE username='".$account_info[username]."' LIMIT 1";
		if (($result = mysql_query($query,$cable_admin_plugin[connector]->db_link)) === false)
			return 'Error reading information from user database table';

		if (mysql_num_rows($result) < 1)
			$error = "Could not find user '".$account_infor[username]."' account information.";
		else
		{
			$account_info = mysql_fetch_assoc($result);
			if (($account_info[adminlevel] > $cable_admin_plugin[connector]->user->values[adminlevel]) && ($cable_admin_plugin[connector]->user->values[adminlevel] < 2))
				$error = "You do not have the necessary privileges to modify that user.";
		}
		/* ban by ip stuff */
		if ($_REQUEST['user_ip'] != '')
			$account_info[fullname] = str_replace('"','',str_replace('\'','',urldecode($_REQUEST['user_ip'])));
		/* full syntax: admin.php?action=edit_users&user_action=edit_account&user_name=(name)&user_ip=(ip) */
	}
	else /* just some user trying to change his account details */
	{
		$account_info[username] = $cable_admin_plugin[connector]->user->values[username];
		$account_info[fullname] = $cable_admin_plugin[connector]->user->values[fullname];
		$account_info[email] = $cable_admin_plugin[connector]->user->values[email];
		$account_info[password] = $cable_admin_plugin[connector]->user->values[password];
		
		/* user must authenticate properly before he's able to change account information */
		$cable_admin_plugin[action_template]->SetBool('CABLE-Authenticate',true);
	}
	
	/* so far so good, check passwords against each other and for suitability */
	if ($error === false)
	{
		/* make sure passwords match */
		if ($_REQUEST['account_password1'] != $_REQUEST['account_password2'])
			$error = 'New passwords did not match.';
		elseif ((strlen($_REQUEST['account_password1']) < 8) && ($_REQUEST['account_password1'] != ''))
			$error = 'New password must be at least 8 characters long.';
		elseif (!CABLE_verifyMailbox($account_info[email]))
			$error = 'Email address is not valid.';
	}
	
	/* update the template to reflect the requested changes */
	foreach($account_info as $field_name => $field_value)
			$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Account.'.$field_name,$field_value);

	if ($error !== false) /* if we had an error, update the template and drop out */
	{
		$cable_admin_plugin[action_template]->SetBool('CABLE-Error',true);
		$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Error.text',$error);
		
		return true;
	}
	
	/* if the form hasn't been submitted, (i.e. just displaying account details) just display the page and exit */
	if ($_REQUEST['account_action'] == '')
		return true;
	
	/* if the user has entered a password, hash it up for insertion */
	if ($_REQUEST['account_password1'] != '')
		$account_info[password] = md5($account_info[username].urldecode($_REQUEST['account_password1']));
	else
		$account_info[password] = $cable_admin_plugin[connector]->user->values[password];
	
	/* update database record with new information */
	$query = "UPDATE $table set fullname='".$account_info[fullname]."',email='".$account_info[email]."',password='".$account_info[password]."' WHERE username='".$account_info[username]."'";
	if (($result = mysql_query($query,$cable_admin_plugin[connector]->db_link)) !== true)
		return 'Error writing user information to database.';
	
	/* write success to template */
	$cable_admin_plugin[action_template]->SetBool('CABLE-Notice',true);
	$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Notice.text','Succesfully updated account details.');
	
	return true;
}

function CABLE_adminUsersList()
{
	global $cable_admin_plugin;
	
	/* user has to be an admin of some kind */
	if ($cable_admin_plugin[connector]->user->values[adminlevel] < 1)
		return true;
		
	/* if we're supposed to be editing a single account, load the account admin instead */
	if (urldecode($_REQUEST['user_action']) == 'edit_account')
		return CABLE_adminAccount();
	
	/* load user template */
	$cable_admin_plugin[action_template] = $cable_admin_plugin[action_template]->GetChild('CABLE-UsersPage');
	if ($cable_admin_plugin[action_template] === false)
		return 'Error retrieving user editing page';
		
	/* load user subtemplate */
	$user_template = $cable_admin_plugin[action_template]->GetChild('CABLE-User');
	if ($user_template === false)
		return 'Error retrieving user subtemplate';
	
	/* load user adminlevel subtemplate */
	$adminlevel_template = $user_template->GetChild('CABLE-UserAdminlevelMenu');
	if ($adminlevel_template === false)
		return 'Error retrieving user adminlevel template';
	
	/* table name upon which to execute the query */
	$table = "cable_".$cable_admin_plugin[connector]->config['TablePrefix']."_users";
		
	$username = str_replace('"','',str_replace('\'','',urldecode($_REQUEST['user_name'])));
	
	/* only administrators beyond this point */
	if ($cable_admin_plugin[connector]->user->values[adminlevel] > 0)
	{
		/* what is the maximum operating level of the current admin? */
		if ($cable_admin_plugin[connector]->user->values[adminlevel] > 1)
			$maxlevel = 3; //unlimited
		else
			$maxlevel = 1;
		
		/* users can only promote other users to one step below their adminlevel */
		$adminlevel = min((int)urldecode($_REQUEST['user_adminlevel']),$maxlevel -1);
		
		/* look up the user in question */
		$query = "SELECT adminlevel FROM $table WHERE (username = '$username') LIMIT 1";
		if (($result = mysql_query($query,$cable_admin_plugin[connector]->db_link)) === false)
			return 'Error retriving user information from database';
	
		$row = mysql_fetch_row($result);
		if ((mysql_num_rows($result) > 0) && ($row[0] < $maxlevel))
		{
			/* perform the requested action */
			switch(urldecode($_REQUEST['user_action']))
			{
				case 'delete':
					if ($username != $cable_admin_plugin[connector]->user->values[username])
						$query = "DELETE FROM $table WHERE username='$username' LIMIT 1";
					break;
				case 'update':
					if ($username != $cable_admin_plugin[connector]->user->values[username])
						$query = "UPDATE $table SET adminlevel = $adminlevel WHERE username='$username' LIMIT 1";
					break;
			}
			if (($result = mysql_query($query,$cable_admin_plugin[connector]->db_link)) === false)
				return 'Error updating user information database';
		}
		
		/* retrieve all user records  */
		$query = "SELECT * FROM $table ";
		if (($result = mysql_query($query,$cable_admin_plugin[connector]->db_link)) === false)
			return 'Error retriving user information from database'.mysql_error();
			
		/* retrieve the admin level titles from the config file */
		$adminlevel_titles = explode(',',$cable_admin_plugin[connector]->config['Adminlevels']);
	
		/* step through each username in the database and append it to the list */
		while(($array = mysql_fetch_assoc($result)) !== false)
		{
			$user_template->Reset();
			
			$user_template->ReplaceInsert('CABLE-User.username',$array['username']);
			$user_template->ReplaceInsert('CABLE-User.fullname',$array['fullname']);
			$user_template->ReplaceInsert('CABLE-User.email',$array['email']);
			
			if ($array['username'] != $cable_admin_plugin[connector]->user->values[username])
				$user_template->SetBool('CABLE-Modify',($array[adminlevel] < $maxlevel));
			else
				$user_template->SetBool('CABLE-Modify',false);
			
			for($i=-1;$i<=min($maxlevel,2);$i++)
			{
				$adminlevel_template->Reset();
				$adminlevel_template->ReplaceInsert('CABLE-UserAdminlevelMenu.value',$i);
				$adminlevel_template->ReplaceInsert('CABLE-UserAdminlevelMenu.title',$adminlevel_titles[$i +1]);
				$adminlevel_template->SetBool('CABLE-UserAdminlevelMenu.selected',$i == $array['adminlevel']);
				$user_template->AppendInsert('CABLE-UserAdminlevelMenu',$adminlevel_template->template);
			}
			$cable_admin_plugin[action_template]->AppendInsert('CABLE-Users',$user_template->template);
		}
	}
	
	return true;
}

function CABLE_verifyMailbox($email)
{
	/* taken from a comment posted on http://www.tellinya.com/read/2007/08/22/59.html */
	list($userName, $mailDomain) = split("@", $email);
	if (@checkdnsrr($mailDomain, "MX"))
		return true;
	else
		return false;
}
?>